// teacher_test1.js
// 全局变量声明
let teacherCourses = [];
let allCourses = [];
const API_BASE_URL = ''; // 根据实际部署环境配置

// 读取 cookie 的函数
function getCookie(name) {
    const cookies = document.cookie.split('; ');
    for (let i = 0; i < cookies.length; i++) {
        const parts = cookies[i].split('=');
        if (parts[0] === name) {
            return decodeURIComponent(parts[1]);
        }
    }
    return null;
}

// 当前教师 ID - 从 cookie 获取
let currentTeacherId = getCookie('user_id');
console.log('当前教师 ID:', currentTeacherId); // 修复这里
if (!currentTeacherId || isNaN(currentTeacherId)) {
    currentTeacherId = null;
} else {
    currentTeacherId = parseInt(currentTeacherId, 10);
}

// 初始化页面
document.addEventListener('DOMContentLoaded', function() {
    // 设置教师姓名
    const teacherName = getCookie('teacher_name') || '教师';
    document.getElementById('teacherName').textContent = teacherName;

    // 默认加载"我的课表"页面
    loadTeacherCourses();

    // 菜单切换逻辑
    const menuItems = document.querySelectorAll('.menu-item');
    menuItems.forEach(item => {
        item.addEventListener('click', function() {
            menuItems.forEach(i => i.classList.remove('active'));
            this.classList.add('active');

            document.querySelectorAll('.page-content').forEach(page => {
                page.style.display = 'none';
            });

            const pageId = this.getAttribute('data-page') + '-page';
            document.getElementById(pageId).style.display = 'block';

            switch(this.getAttribute('data-page')) {
                case 'my-courses':
                    loadTeacherCourses();
                    break;
                case 'grade-management':
                    loadCoursesForGrading();
                    break;
                case 'select-courses':
                    loadAvailableCourses();
                    break;
                case 'my-students':
                    loadCoursesForStudents();
                    break;
            }
        });
    });

    // 退出登录
    document.getElementById('logoutBtn').addEventListener('click', function() {
        if (confirm('确定要退出登录吗？')) {
            // 清除cookie
            document.cookie = 'user_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
            document.cookie = 'teacher_name=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
            window.location.href = 'index.html'; // 改为登录页
        }
    });

    // 课程选择事件 - 成绩管理
    document.getElementById('course-select').addEventListener('change', function() {
        const courseId = this.value;
        if (courseId) {
            loadStudentsForGrading(courseId);
        } else {
            document.getElementById('course-students-container').style.display = 'none';
        }
    });

    // 课程选择事件 - 班级学生
    document.getElementById('student-course-select').addEventListener('change', function() {
        const courseId = this.value;
        if (courseId) {
            loadStudentsForCourse(courseId);
        } else {
            document.getElementById('student-list-container').style.display = 'none';
        }
    });

    // 模态框控制
    document.getElementById('closeGradeModal').addEventListener('click', closeGradeModal);
    document.getElementById('cancelGrade').addEventListener('click', closeGradeModal);
    document.getElementById('saveGrade').addEventListener('click', saveStudentGrade);
    document.getElementById('closeSelectModal').addEventListener('click', closeSelectModal);
    document.getElementById('cancelSelect').addEventListener('click', closeSelectModal);
    document.getElementById('confirmSelect').addEventListener('click', confirmCourseSelection);
});

// 关闭成绩模态框
function closeGradeModal() {
    document.getElementById('gradeModal').style.display = 'none';
}

// 关闭选课模态框
function closeSelectModal() {
    document.getElementById('selectCourseModal').style.display = 'none';
}

// 加载教师课程
function loadTeacherCourses() {
    const container = document.getElementById('my-courses-container');
    const table = container.querySelector('table');
    const loading = container.querySelector('.loading');
    const errorDiv = document.getElementById('my-courses-error');

    loading.style.display = 'block';
    table.style.display = 'none';
    errorDiv.style.display = 'none';

    // 添加时间戳防止缓存
    fetch(`/teacher/courses/${currentTeacherId}?t=${Date.now()}`)
        .then(response => response.json())
        .then(data => {
            loading.style.display = 'none';

            if (data.code === 200) {
                teacherCourses = data.data;
                renderTeacherCourses(teacherCourses);
                table.style.display = 'table';
            } else {
                errorDiv.textContent = data.msg || '获取课程列表失败';
                errorDiv.style.display = 'block';
            }
        })
        .catch(error => {
            loading.style.display = 'none';
            errorDiv.textContent = '网络错误，请稍后重试';
            errorDiv.style.display = 'block';
            console.error('获取教师课程出错:', error);
        });
}

// 渲染教师课程
function renderTeacherCourses(courses) {
    const tableBody = document.getElementById('my-courses-table');
    tableBody.innerHTML = '';

    if (!courses || courses.length === 0) {
        tableBody.innerHTML = '<tr><td colspan="4" style="text-align: center;">暂无课程数据</td></tr>';
        return;
    }

    courses.forEach(course => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${course.id}</td>
            <td>${course.cname || '未知课程'}</td>
            <td>${course.chours || 0}课时</td>
            <td>${formatDate(course.createdAt) || '未知时间'}</td> <!-- 格式化日期 -->
        `;
        tableBody.appendChild(row);
    });
}

// 日期格式化函数
function formatDate(dateString) {
    if (!dateString) return null;
    const date = new Date(dateString);
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
}

// 加载成绩管理课程
function loadCoursesForGrading() {
    const courseSelect = document.getElementById('course-select');

    // 清空现有选项（保留第一个选项）
    while (courseSelect.options.length > 1) {
        courseSelect.remove(1);
    }

    // 添加教师课程到下拉框
    teacherCourses.forEach(course => {
        const option = document.createElement('option');
        option.value = course.id;
        option.textContent = course.cname || `课程ID: ${course.id}`;
        courseSelect.appendChild(option);
    });
}

// 加载班级学生课程
function loadCoursesForStudents() {
    const courseSelect = document.getElementById('student-course-select');

    // 清空现有选项（保留第一个选项）
    while (courseSelect.options.length > 1) {
        courseSelect.remove(1);
    }

    // 添加教师课程到下拉框
    teacherCourses.forEach(course => {
        const option = document.createElement('option');
        option.value = course.id;
        option.textContent = course.cname || `课程ID: ${course.id}`;
        courseSelect.appendChild(option);
    });
}

// 加载学生列表用于成绩管理
function loadStudentsForGrading(courseId) {
    const container = document.getElementById('course-students-container');
    const studentsList = document.getElementById('students-list');

    studentsList.innerHTML = '<div class="loading">加载学生列表...</div>';
    container.style.display = 'block';

    fetch(`/teacher/course/${courseId}/students?t=${Date.now()}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                renderStudentsForGrading(data.data, courseId);
            } else {
                studentsList.innerHTML = `<div class="error-message">${data.msg || '获取学生列表失败'}</div>`;
            }
        })
        .catch(error => {
            studentsList.innerHTML = `<div class="error-message">网络错误，请稍后重试</div>`;
            console.error('获取学生列表出错:', error);
        });
}

// 渲染学生列表用于成绩管理
function renderStudentsForGrading(students, courseId) {
    const studentsList = document.getElementById('students-list');
    studentsList.innerHTML = '';

    if (!students || students.length === 0) {
        studentsList.innerHTML = '<div class="no-data">该课程暂无学生</div>';
        return;
    }

    students.forEach(student => {
        const studentCard = document.createElement('div');
        studentCard.className = 'student-card';

        studentCard.innerHTML = `
            <div class="student-info">
                <div class="student-name">${student.sname}</div>
                <div class="student-score">成绩: 
                    <span id="score-${student.userId}">${student.score ?? '未录入'}</span>
                </div>
            </div>
            <div class="student-actions">
                <button class="action-btn update-btn" 
                        data-student-id="${student.userId}" 
                        data-student-name="${student.sname}"
                        data-course-id="${courseId}">
                    ${student.score ? '修改成绩' : '录入成绩'}
                </button>
            </div>
        `;

        studentsList.appendChild(studentCard);
    });

    // 绑定录入/修改成绩按钮事件
    document.querySelectorAll('.update-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const studentId = this.getAttribute('data-student-id');
            const studentName = this.getAttribute('data-student-name');
            const courseId = this.getAttribute('data-course-id');
            const currentScore = document.getElementById(`score-${studentId}`).textContent;

            document.getElementById('gradeModalTitle').textContent = currentScore === '未录入' ? '录入成绩' : '修改成绩';
            document.getElementById('student-name').value = studentName;

            // 获取课程名称
            const courseName = teacherCourses.find(c => c.id == courseId)?.cname || '未知课程';
            document.getElementById('course-name').value = courseName;

            document.getElementById('score-input').value = currentScore === '未录入' ? '' : currentScore;
            document.getElementById('score-student-id').value = studentId;
            document.getElementById('score-course-id').value = courseId;

            document.getElementById('gradeModal').style.display = 'flex';
        });
    });
}

// 加载班级学生
function loadStudentsForCourse(courseId) {
    const container = document.getElementById('student-list-container');
    const tableBody = document.getElementById('student-list-table');

    tableBody.innerHTML = '<tr><td colspan="4" style="text-align: center;">加载中...</td></tr>';
    container.style.display = 'block';

    // 调用API获取学生列表
    fetch(`/teacher/course/${courseId}/students?t=${Date.now()}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                renderStudentsForCourse(data.data);
            } else {
                tableBody.innerHTML = `<tr><td colspan="4" style="text-align: center; color: red;">${data.msg || '获取学生列表失败'}</td></tr>`;
            }
        })
        .catch(error => {
            tableBody.innerHTML = '<tr><td colspan="4" style="text-align: center; color: red;">网络错误，请稍后重试</td></tr>';
            console.error('加载学生失败:', error);
        });
}

// 渲染班级学生
function renderStudentsForCourse(students) {
    const tableBody = document.getElementById('student-list-table');
    tableBody.innerHTML = '';

    if (!students || students.length === 0) {
        tableBody.innerHTML = '<tr><td colspan="4" style="text-align: center;">该课程暂无学生</td></tr>';
        return;
    }

    students.forEach(student => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${student.sno}</td>
            <td>${student.sname}</td>
            <td>${student.gender || '未知'}</td>
            <td>${student.score !== null ? student.score : '未录入'}</td>
        `;
        tableBody.appendChild(row);
    });
}

// 保存学生成绩
function saveStudentGrade() {
    const studentId = document.getElementById('score-student-id').value;
    const courseId = document.getElementById('score-course-id').value;
    const scoreValue = document.getElementById('score-input').value;

    if (!scoreValue) {
        alert('请输入成绩');
        return;
    }

    // 修改1: 使用浮点数而非整数
    const scoreData = {
        student_id: parseInt(studentId),
        course_id: parseInt(courseId),
        score: parseFloat(scoreValue), // 改为parseFloat
    };

    // 确定是录入还是更新
    const isNewScore = document.getElementById('gradeModalTitle').textContent === '录入成绩';
    const endpoint = isNewScore ? '/teacher/score/insert' : '/teacher/score/update';

    fetch(endpoint, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(scoreData)
    })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('成绩保存成功');
                closeGradeModal();

                // 更新页面显示
                document.getElementById(`score-${studentId}`).textContent = scoreValue;
                document.querySelector(`.update-btn[data-student-id="${studentId}"]`)
                    .textContent = '修改成绩';

                // 刷新学生列表
                loadStudentsForGrading(courseId);
            } else {
                alert('成绩保存失败: ' + (data.msg || '未知错误'));
            }
        })
        .catch(error => {
            console.error('保存成绩出错:', error);
            alert('保存成绩失败，请稍后重试');
        });
}
// 加载可选课程
function loadAvailableCourses() {
    const container = document.getElementById('available-courses-container');
    const courseList = document.getElementById('available-courses-list');
    const loading = container.querySelector('.loading');
    const errorDiv = document.getElementById('available-courses-error');

    loading.style.display = 'block';
    courseList.style.display = 'none';
    errorDiv.style.display = 'none';

    fetch(`/course/query?t=${Date.now()}`)
        .then(response => response.json())
        .then(data => {
            loading.style.display = 'none';

            if (data.code === 200) {
                allCourses = data.data;
                renderAvailableCourses(allCourses);
                courseList.style.display = 'grid';
            } else {
                errorDiv.textContent = data.msg || '获取可选课程失败';
                errorDiv.style.display = 'block';
            }
        })
        .catch(error => {
            loading.style.display = 'none';
            errorDiv.textContent = '网络错误，请稍后重试';
            errorDiv.style.display = 'block';
            console.error('获取可选课程出错:', error);
        });
}

// 渲染可选课程
function renderAvailableCourses(courses) {
    const coursesList = document.getElementById('available-courses-list');
    coursesList.innerHTML = '';

    if (!courses || courses.length === 0) {
        coursesList.innerHTML = '<div class="no-data">当前没有可选课程</div>';
        return;
    }

    // 过滤掉教师已选的课程
    const availableCourses = courses.filter(course =>
        !teacherCourses.some(tc => tc.id === course.id)
    );

    if (availableCourses.length === 0) {
        coursesList.innerHTML = '<div class="no-data">您已选择所有课程</div>';
        return;
    }

    availableCourses.forEach(course => {
        const courseCard = document.createElement('div');
        courseCard.className = 'course-card';
        courseCard.innerHTML = `
            <div class="course-name">${course.cname || '未知课程'}</div>
            <div class="course-info">课时: ${course.chours || 0}课时</div>
            <div class="course-info">授课教师: ${course.teacherName || '未知教师'}</div>
            <div class="course-info">状态: ${course.status || '未选'}</div>
            <div style="margin-top: 10px;">
                <input type="checkbox" id="course-${course.id}" 
                       class="course-checkbox" 
                       data-course-id="${course.id}" 
                       data-course-name="${course.cname || '未知课程'}">
                <label for="course-${course.id}">选择此课程</label>
            </div>
        `;
        coursesList.appendChild(courseCard);
    });

    // 显示选课按钮
    const selectButton = document.createElement('button');
    selectButton.className = 'btn btn-primary';
    selectButton.textContent = '提交选课';
    selectButton.style.marginTop = '20px';
    selectButton.addEventListener('click', showCourseSelectionModal);
    coursesList.appendChild(selectButton);
}

// 显示选课确认模态框
function showCourseSelectionModal() {
    const selectedCourses = [];

    // 获取所有选中的课程
    document.querySelectorAll('.course-checkbox:checked').forEach(checkbox => {
        selectedCourses.push({
            id: checkbox.getAttribute('data-course-id'),
            name: checkbox.getAttribute('data-course-name')
        });
    });

    if (selectedCourses.length === 0) {
        alert('请至少选择一门课程');
        return;
    }

    // 更新模态框内容
    const coursesList = document.getElementById('selected-courses-list');
    coursesList.innerHTML = '';

    selectedCourses.forEach(course => {
        const courseItem = document.createElement('div');
        courseItem.textContent = course.name;
        coursesList.appendChild(courseItem);
    });

    // 显示模态框
    document.getElementById('selectCourseModal').style.display = 'flex';
}

// 确认选课
function confirmCourseSelection() {
    const selectedCourseIds = [];

    // 获取所有选中的课程ID
    document.querySelectorAll('.course-checkbox:checked').forEach(checkbox => {
        selectedCourseIds.push(parseInt(checkbox.getAttribute('data-course-id')));
    });

    const teacherCourseInfo = {
        teacher_id: currentTeacherId,
        courses: selectedCourseIds
    };

    fetch('/teacher/courses/insert', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(teacherCourseInfo)
    })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('选课成功');
                closeSelectModal();

                // 刷新课程列表
                loadTeacherCourses();
                loadAvailableCourses();
            } else {
                alert('选课失败: ' + (data.msg || '未知错误'));
            }
        })
        .catch(error => {
            console.error('选课出错:', error);
            alert('选课失败，请稍后重试');
        });
}